﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using CompanyHub.Helpers;
using CompanyHub.Resources;
using Microsoft.Phone;
using Windows.ApplicationModel;
using Windows.Foundation;
using Windows.Management.Deployment;
using Windows.Phone.Management.Deployment;
using Windows.Phone.Storage.SharedAccess;
using Windows.Storage;
using Windows.Storage.Streams;

namespace CompanyHub.ViewModels
{
    public class MainViewModel : BindableBase
    {
        public MainViewModel()
        {
            _companyApps = new ObservableCollection<AppInfo>();
            _installedApps = new ObservableCollection<InstalledApp>();
        }

        /// <summary>
        ///     Sample property that returns a localized string
        /// </summary>
        public string LocalizedSampleProperty
        {
            get { return AppResources.SampleProperty; }
        }

        public bool IsDataLoaded { get; private set; }

        /// <summary>
        ///    载入数据
        /// </summary>
        public async Task LoadData()
        {
            await LoadCompanyApps();
            await LoadInstalledApps();
            IsDataLoaded = true;
        }

        #region apps for me
        const string keyName = "AppList";

        private ObservableCollection<AppInfo> _companyApps;
        public ObservableCollection<AppInfo> CompanyApps
        {
            get
            {
                return _companyApps;
            }
        }

        //通过网络接口获得所有企业应用的列表
        private async Task LoadCompanyApps()
        {
            _companyApps.Clear();

            string jsonString = string.Empty;

            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                var webClient = new WebClient();
                webClient.Encoding = Encoding.UTF8;

                jsonString =
                   await
                   webClient.DownloadStringTask(new Uri("http://118.192.24.19/app/wp8/AppList.json"));

                if (!IsolatedStorageSettings.ApplicationSettings.Contains(keyName))
                    IsolatedStorageSettings.ApplicationSettings.Add(keyName, string.Empty);

                IsolatedStorageSettings.ApplicationSettings[keyName] = jsonString;
            }
            else
            {
                if (!IsolatedStorageSettings.ApplicationSettings.TryGetValue(keyName, out jsonString))
                    return;
            }

            var result = JsonHelper.Deserialize<List<AppInfo>>(jsonString);

            List<string> installedAppId = InstallationManager
                .FindPackagesForCurrentPublisher()
                .Select(a => a.Id.ProductId.ToLower())
                .ToList();

            foreach (AppInfo item in result)
            {
                _companyApps.Add(item);
                if (installedAppId.Contains(item.Id.ToLower()))
                {
                    item.InstallState = AppInfo.PackageInstallState.Installed;
                }
                else
                {
                    item.InstallState = AppInfo.PackageInstallState.NotInstalled;
                }
            }
        }


        public class AppInfo : BindableBase
        {
            //描述企业应用的状态
            public enum PackageInstallState
            {
                //未安装
                NotInstalled = 0,
                //正在安装
                Installing = 1,
                //已安装
                Installed = 2
            }

            
            //企业应用的 Product ID
            public string Id { get; set; }
            
            //企业应用的 XAP 地址
            public string Url { get; set; }
            
            //企业应用名称
            public string Name { get; set; }
            
            //企业应用功能描述
            public string Detail { get; set; }

            //企业应用图标地址
            private string _ImageUri;
            public string ImagePath
            {
                get { return _ImageUri; }
                set
                {
                    if (_ImageUri == value)
                        return;

                    _ImageUri = value;
                    NotifyPropertyChanged("ImagePath");
                    NotifyPropertyChanged("LoadedSource");
                }
            }

            [IgnoreDataMember]
            public ImageSource LoadedSource
            {
                get
                {
                    var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
                    if (ImagePath.Contains("http"))
                    {
                        return new BitmapImage(new Uri(_ImageUri));
                    }
                    else
                    {
                        BitmapImage image = new BitmapImage();
                        IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
                        string isoFilename = _ImageUri;
                        var stream = isoStore.OpenFile(isoFilename, System.IO.FileMode.Open);
                        image.SetSource(stream);
                        return image;
                    }
                }
            }

            //安装状态
            private PackageInstallState _installState = PackageInstallState.NotInstalled;
            public PackageInstallState InstallState
            {
                get { return _installState; }
                set
                {
                    if (_installState == value)
                        return;

                    _installState = value;
                    NotifyPropertyChanged("InstallState");
                }
            }


            //安装进度
            private uint _InstalltionProgressPercent = 0;
            public uint InstalltionProgressPercent
            {
                get { return _InstalltionProgressPercent; }
                set
                {
                    if (value == _InstalltionProgressPercent)
                        return;
                    _InstalltionProgressPercent = value;
                    NotifyPropertyChanged("InstalltionProgressPercent");
                }
            }
        }


        private IEnumerable<Package> GetPendingPackage()
        {
            var result = InstallationManager.GetPendingPackageInstalls();
            throw new NotImplementedException();
        }
        #endregion

        #region Installed Apps

        private readonly ObservableCollection<InstalledApp> _installedApps;

        public ObservableCollection<InstalledApp> installedApps
        {
            get { return _installedApps; }
        }

        //获得已安装程序列表
        public async Task LoadInstalledApps()
        {
            installedApps.Clear();

            foreach (Package item in InstallationManager.FindPackagesForCurrentPublisher())
            {
                //if (item.Equals(Package.Current))
                //    continue;

                //还没有找到好的方法从已安装程序列表中过滤企业中心自身
                if (item.Id.Name.Equals("企业中心")) continue;

                var currentinstalledApp = new InstalledApp(item);
                installedApps.Add(currentinstalledApp);
            }
        }

        public class InstalledApp
        {
            private static string ROUTES_FOLDER_NAME = "ROUTES_FOLDER";


            //当前企业应用所对应的 Package 对象
            private readonly Package currentApp;

            
            public InstalledApp(Package app)
            {
                currentApp = app;
            }

            //企业应用的 Product Id
            public string Id
            {
                get { return currentApp.Id.ProductId; }
            }

            //企业应用图标地址
            private string _imagePath;
            public string ImagePath
            {
                get { return _imagePath; }
            }

            //企业应用名称
            public string Name
            {
                get { return currentApp.Id.Name; }
            }
            
            //更新程序图标
            public async Task LoadAppICON()
            {
                _imagePath = await ProcessExternalFile(currentApp.GetThumbnailToken());
            }

            //启动当前企业应用
            public void Launch(string parameter = "")
            {
                try
                {
                    currentApp.Launch(parameter);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }

            // 根据 fileToken 获取文件
            public async Task<string> ProcessExternalFile(string fileToken)
            {
                // 创建缓存文件夹
                IStorageFolder routesFolder =
                    await
                    ApplicationData.Current.LocalFolder.CreateFolderAsync(ROUTES_FOLDER_NAME,
                                                                          CreationCollisionOption.OpenIfExists);

                // 获取文件名
                string incomingRouteFilename = SharedStorageAccessManager.GetSharedFileName(fileToken);

                // 复制到缓存文件夹
                IStorageFile routeFile =
                    await
                    SharedStorageAccessManager.CopySharedFileAsync((StorageFolder)routesFolder, incomingRouteFilename,
                                                                   NameCollisionOption.GenerateUniqueName, fileToken);

                return routeFile.Path;
            }
        }
        #endregion
    }
}
